/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jogs.client;

/**
 *
 * @author Dactry
 */
public class TabThread extends Thread
{
  TabInfo tabInfo;
  private boolean connected;
  public TabThread(TabInfo _tabInfo)
  {
  	connected = true;
    tabInfo = _tabInfo;
  }

  public int getIndex() 
  {
    return tabInfo.getIndex(); 
  }

  private boolean isRoomTab() { return tabInfo.type == 2; }
  private boolean isTableTab() { return tabInfo.type == 3; }


  public void sendCommand(String line)
  {
    System.out.println("sendCommand(" + line + ") tabIndex = " + getIndex() + ", type = " + tabInfo.type);
    
    if (line.startsWith("/sit ") && isRoomTab())
    {
      // handle sitting at a table

      String parts[] = line.split(" ");
      String tableName = parts[1];
      tabInfo.out.println("@SIT:" + tableName);
    }
    else if (line.startsWith("/create ") && isTableTab())
    {
      // handle sitting at a table

      String parts[] = line.split(" ");
      String gameType = parts[1];
      tabInfo.out.println("@CREATE:" + gameType);
    }
    else if (line.startsWith("/leave"))
    {
    	tabInfo.out.println("@LEAVE:");
    	connected = false;
    	tabInfo.close();
    }
    else if (line.startsWith("/"))
    {
      // invalid command
      String[] parts = line.split(" ");
      tabInfo.append("Invalid command: " + parts[0], "error");
    }
    else
    {
      System.out.println("Sending @CHAT:"+line.trim());
      tabInfo.out.println("@CHAT:" + line.trim());
    }
  }
  
  public void handleChat(String details)
  {
    tabInfo.append(details, "regular");
  }

  private void handleAllInfo(String details)
  {
  	String[] parts = details.split(":");
  	for (String info : parts)
  	{
  		if(info.startsWith("@TABLE"))
  		{
  			String[] table = info.split(",");
  			String name = table[0].split(";")[1] + " (" + table[1] + ")";
  			ListObject lo = new ListObject(name, 2, tabInfo.getPrintStream(), Integer.parseInt(table[2]), table[3]);
  			this.tabInfo.getListModel().addElement(lo);
  		}
  		else if (info.startsWith("@USER"))
  		{
  			ListObject lo = new ListObject(info.split(";")[1], 1, tabInfo.getPrintStream());
  			tabInfo.getListModel().addElement(lo);
  		}
  	}
  }
  
  private void handleTableUpdate(String details)
  {
  	System.out.println(details);
  }
  
  public void handleEntered(String details)
  {
    tabInfo.append(details + " has entered the room.", "regular"); 
    tabInfo.getListModel().addElement(new ListObject(details, 1, tabInfo.getPrintStream()));
  }

  public void handleSat(String details)
  {
    tabInfo.append(details + " has sat down at the table.", "regular");
    tabInfo.getListModel().addElement(new ListObject(details, 1, tabInfo.getPrintStream()));
  }

  public void handleSit(String details)
  {
    // @OKSIT:table,host,port,keypass
    String parts[] = details.split(",");

    System.out.println("Sitting " + details);
    
    String table = parts[0];
    String host = parts[1];
    int port = Integer.parseInt(parts[2]);
    String keypass = parts[3];

    tabInfo.getParent().spawnTabThread(table, host, port, keypass, 3);
  }

  public void handleNewGame(String details)
  {
    // here's where we should change the tab.. replace the text pane
    // with the game's panel
    String[] statusparts = details.split(",");
    tabInfo.parent.createGame(statusparts[0], getIndex());
    //tabInfo.append("New game created: " + details, "regular");
  }

  public void handleErrorCreate(String details)
  {
    tabInfo.append("Create failed: " + details, "error");
  }

  public void handleErrorSit(String details)
  {
    tabInfo.append("Sit failed: " + details, "error");
  }


  @Override
  public void run()
  {
    try
    {
      tabInfo.textPane.setText("");

      String line = "";

      while (connected && line != null)
      {
        line = tabInfo.in.readLine();

      	if(line == null)
        {
          System.out.println("Received: null");
          break;
        }

        line = line.trim(); 

        String details = null;
        String command = null;


        //all commands start with a @ and end with a :
        int begin = line.indexOf('@');
        int end = line.indexOf(':');

        //if @ and : are not in message than it is not a command
        if(begin == -1 || end == -1)
        {
        	//this.send("@ERROR:Not a valid command");
          System.out.println("Bad command: " + line);
          continue;
        }

        //get the command out of the message
        command = line.substring(begin, end);

        //if command has details
        if(line.length() > end+1)
          details = line.substring(end+1);


        //tabInfo.append(line + "\n", "regular");

        if (command.equals("@CHAT"))
          handleChat(details);
        else if (command.equals("@ENTERED"))
          handleEntered(details);
        else if (command.equals("@OKSIT") && isRoomTab())
          handleSit(details);
        else if (command.equals("@SAT") && isTableTab())
          handleSat(details); 
        else if (command.equals("@ALLINFO"))
        	handleAllInfo(details);
        else if (command.equals("@UPDATETABLE"))
        	handleTableUpdate(details);
        else if (command.equals("@ERROR_SIT"))
        	handleErrorSit(details);
        else if (command.equals("@ERROR_CREATE"))
        	handleErrorCreate(details);
        else if (command.equals("@NEWGAME"))
        	handleNewGame(details);
        else
          System.out.println("Command unhandled: " + line);
      }
    }
    catch(Exception e)
    {
    	if(connected)
    		e.printStackTrace();
    }
  }
 }